const Permission = require('../models/Permission');

// 创建权限
exports.createPermission = async (req, res) => {
  try {
    const permission = new Permission(req.body);
    await permission.save();
    res.json(permission);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 获取权限列表
exports.getPermissions = async (req, res) => {
  try {
    const permissions = await Permission.find();
    res.json(permissions);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 分页获取权限列表
exports.getPermissionPage = async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const skip = (page - 1) * limit;

    const permissions = await Permission.find()
      .skip(skip)
      .limit(limit);

    const totalPermissions = await Permission.countDocuments();

    res.json({
      permissions,
      currentPage: page,
      totalPages: Math.ceil(totalPermissions / limit),
      totalPermissions
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 根据 ID 获取权限
exports.getPermissionById = async (req, res) => {
  try {
    const permission = await Permission.findById(req.params.id);
    if (!permission) {
      return res.status(404).json({ message: '权限未找到' });
    }
    res.json(permission);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 更新权限
exports.updatePermission = async (req, res) => {
  try {
    const permission = await Permission.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!permission) {
      return res.status(404).json({ message: '权限未找到' });
    }
    res.json(permission);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};

// 删除权限
exports.deletePermission = async (req, res) => {
  try {
    const permission = await Permission.findByIdAndDelete(req.params.id);
    if (!permission) {
      return res.status(404).json({ message: '权限未找到' });
    }
    res.json({ message: '权限删除成功' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};